package com.jirong.shop.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jirong.shop.mapper.TOrderMapper;
import com.jirong.shop.pojo.TOrder;
import com.jirong.shop.pojo.TSeckillGoods;
import com.jirong.shop.pojo.TSeckillOrder;
import com.jirong.shop.pojo.TUser;
import com.jirong.shop.service.TGoodsService;
import com.jirong.shop.service.TOrderService;
import com.jirong.shop.service.TSeckillOrderService;
import com.jirong.shop.utils.JsonUtil;
import com.jirong.shop.utils.MD5Util;
import com.jirong.shop.utils.UUIDUtil;
import com.jirong.shop.vo.GoodsVo;
import com.jirong.shop.vo.OrderDetailVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author jirong
 * @since 2022-01-16
 */
@Service
public class TOrderServiceImpl extends ServiceImpl<TOrderMapper, TOrder> implements TOrderService {
    @Autowired
    private TSeckillGoodsServiceImpl seckillGoodsService;
    @Autowired
    private TOrderMapper orderMapper;
    @Autowired
    private TSeckillOrderService seckillOrderService;
    @Autowired
    private TGoodsService goodsService;
    @Autowired
    @Qualifier("redisTemplate1")
    private RedisTemplate redisTemplate;
//    解决同一用户同时秒杀多件商品。
//    可以通过数据库建立唯一索引避免

    /**
     * 下订单减商品库存
     */
    @Override
//    事务处理
    @Transactional
    public TOrder secKill(TUser user, GoodsVo goods) {
        ValueOperations valueOperations = redisTemplate.opsForValue();
        //秒杀商品表减库存,getOne是service层独有的
        TSeckillGoods seckillGoods = seckillGoodsService.getOne(new
                QueryWrapper<TSeckillGoods>().eq("goods_id",
                goods.getId()));
        seckillGoods.setStockCount(seckillGoods.getStockCount() - 1);
//        更新操作加了限制带上了商品id,这样库存没问题了，但订单数据和秒杀订单有问题
        //    乐观锁来避免高并发问题（法二）
//        boolean seckillGoodsResult = seckillGoodsService.update(new UpdateWrapper<TSeckillGoods>().set("stock_count",
//                seckillGoods.getStockCount()-1).eq("id", goods.getId()).gt("stock_count",
//                0));
//        这里把减一操作和判断大于0操作一起进行，具有原子性
        boolean seckillGoodsResult = seckillGoodsService.update(new UpdateWrapper<TSeckillGoods>().setSql("stock_count=stock_count-1")
                .eq("id", goods.getId())
                .gt("stock_count", 0));
//        查出的类进行更新
//        seckillGoodsService.updateById(seckillGoods);
//        生成订单
//        if (!seckillGoodsResult) {
//            return null;
//        }
        if (seckillGoods.getStockCount() < 1) {
            //判断是否还有库存
            valueOperations.set("isStockEmpty:" + goods.getId(), "0");
            return null;
        }
        TOrder order = new TOrder();
        order.setUserId(user.getId());
        order.setGoodsId(goods.getId());
        order.setDeliveryAddrId(0L);
        order.setGoodsName(goods.getGoodsName());
        order.setGoodsCount(1);
        order.setGoodsPrice(seckillGoods.getSeckillPrice());
        order.setOrderChannel(1);
        order.setStatus(0);
        order.setCreateDate(new Date());
//        增删改查上底层
        orderMapper.insert(order);
//        生成秒杀订单
        TSeckillOrder seckillOrder = new TSeckillOrder();
        seckillOrder.setOrderId(order.getId());
        seckillOrder.setUserId(user.getId());
        seckillOrder.setGoodsId(goods.getId());
//        mybatis-plus的save方法
        seckillOrderService.save(seckillOrder);
//        将秒杀订单放入redis中，更具用户id+商品id识别，网络传输靠json
//        redisTemplate.opsForValue().set("order:"+user.getId()+":"+goods.getId(),seckillOrder);
//        类型一样不容易报错
        valueOperations.set("order:" + user.getId() + ":" + goods.getId(), JsonUtil.object2JsonStr(seckillOrder));
//        换底层添加一样的结果
        return order;
    }

    @Override
    public OrderDetailVo detail(Long orderId) {
        TOrder order = orderMapper.selectById(orderId);
        GoodsVo goodsVo = goodsService.findGoodsVoByGoodsId(order.getGoodsId());
        OrderDetailVo detail = new OrderDetailVo();
        detail.setGoodsVo(goodsVo);
        detail.setOrder(order);
        return detail;
    }

    @Override
    public boolean checkPath(TUser user, Long goodsId, String path) {
//        健壮性验证,从0计数数据库
        if (user == null || StringUtils.isEmpty(path) || goodsId < 0) {
            return false;
        }
//        与缓存对比.cast方式转类型
        String redisPath = (String) redisTemplate.opsForValue().get("seckillPath:" + user.getId() + ":" + goodsId);
        return path.equals(redisPath);
    }
/*
验证图片
 */

    @Override
    public boolean checkCaptcha(TUser user, Long goodsId, String captcha) {
        if (StringUtils.isEmpty(captcha) || null == user || goodsId < 0) {
            return false;
        }
        String redisCaptcha = (String) redisTemplate.opsForValue().get("captcha:" + user.getId() + ":" + goodsId);
        return captcha.equals(redisCaptcha);
    }

    /*
            生成秒杀接口
                 */
    @Override
    public String createPath(TUser user, Long goodsId) {
//        /秒杀地址用MD5加UUID构建
        String str = MD5Util.md5(UUIDUtil.uuid() + "123456");
//        将地址放入缓存中设置过期时间，每一个接口对应相应用户id+商品Id
        redisTemplate.opsForValue().set("seckillPath:" + user.getId() + ":" + goodsId, str, 60, TimeUnit.SECONDS);
        return str;
    }
}
